<template>
  <view>
    <view v-if="operationPanel">
      <view class="xylink-operate-box2 disFlxCC">
        通话时长:{{ callTimeText }}
      </view>

      <view class="xylink-operate-box disFlxJS">
        <view class="disFlxCC" @click="onChangeMuted">
          <image
            v-if="muted"
            src="https://onelive.obs.cn-south-1.myhuaweicloud.com/uniapp/static/yuying2.png"
            style="width: 30px; height: 30px"
          />
          <image
            v-else
            src="https://onelive.obs.cn-south-1.myhuaweicloud.com/uniapp/static/yuying.png"
            style="width: 30px; height: 30px"
          />
          <view class="pt-3">{{ muted ? "解除静音" : "静音" }}</view>
        </view>
        <view class="disFlxCC" @click="onSwitchCamera">
          <image
            v-if="camera"
            src="@/static/image/image220701(22).png"
            style="width: 30px; height: 30px"
          />
          <image
            v-else
            src="@/static/image/image220701(23).png"
            style="width: 30px; height: 30px"
          />
          <view class="pt-3">{{ camera ? "关闭视频" : "开启视频" }}</view>
        </view>
        <view class="disFlxCC" @click="onSwitchPosition">
          <image
            src="@/static/image/image220701(24).png"
            style="width: 30px; height: 30px"
          />
          <view class="pt-3">翻转</view>
        </view>
        <view class="disFlxCC" @click="openMemberShow">
          <image
            src="@/static/image/image220701(26).png"
            style="width: 30px; height: 30px"
          />
          <view class="pt-3">成员({{ template.detail.length }})</view>
        </view>
        <view class="disFlxCC" @click="onStopMeeting">
          <view class="disFlxAC closeBtn">
            <image
              src="@/static/image/image220701(21).png"
              style="width: 30px; height: 30px"
            />
            <text class="pl-7">挂断</text>
          </view>
        </view>
      </view>
    </view>
    <xylink-room
      :template="template"
      :beauty="6"
      :muted="muted"
      :camera="camera"
      :devicePosition="devicePosition"
      waitingImage="https://devcdn.xylink.com/assets/common/img/bg-theme.jpg"
      debug
      id="xylink"
      @onRoomEvent="onRoomEvent($event, { tagId: 'xylink' })"
    ></xylink-room>

    <u-modal
      :show="coloseShow"
      width="295px"
      content="当前服务还在进行中,是否离开?"
      :showCancelButton="true"
      @cancel="coloseShow = false"
      @confirm="sureStopMeeting"
    ></u-modal>
    <u-popup
      :show="memberShow"
      mode="right"
      bgColor="#333333"
      :overlayOpacity="0"
      closeOnClickOverlay
      @close="memberShow = false"
    >
      <view class="colorF memberListBox">
        <view class="title">会议成员({{ template.detail.length }})</view>
        <scroll-view scroll-y class="scrollBox">
          <view
            class="forBox"
            v-for="(item, index) in template.detail"
            :key="index"
          >
            <view class="disFlxAC">
              <view style="margin-right: 5px;">
                <image
                  v-if="(item.roster && item.roster.videoTxMute) || (xy_userInfo.callNumber === item.callNumber && !camera)"
                  src="@/static/image/image220701(23).png"
                  style="width: 20px; height: 20px"
                />
                <image
                  v-else
                  src="@/static/image/image220701(22).png"
                  style="width: 20px; height: 20px"
                />
              </view>
              <view style="margin-right: 5px;">
                <image
                  v-if="(item.roster && item.roster.audioTxMute) || (xy_userInfo.callNumber === item.callNumber && muted)"
                  src="https://onelive.obs.cn-south-1.myhuaweicloud.com/uniapp/static/yuying2.png"
                  style="width: 20px; height: 20px"
                />
                <image
                  v-else
                  src="https://onelive.obs.cn-south-1.myhuaweicloud.com/uniapp/static/yuying.png"
                  style="width: 20px; height: 20px"
                />
              </view>
              <view style="width:135px;" class="ov-1">{{ item.name }}</view>
            </view>
            <view v-if="item.callNumber === currentCallNumber || isMyself" class="btn2">主屏模式</view>
            <view v-else class="btn1" @click="_templateFn(item.callNumber)">设为主屏</view>
          </view>
        </scroll-view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import XYRTC from "@/utils/xy/xy-mp-sdk";
const XYClient = XYRTC.createClient();

export default {
  computed: {
    // 用户信息
    userInfo() {
      return this.$store.state.userInfo;
    },
    // 小鱼会议信息
    cellInfo() {
      return this.$store.state.cellInfo;
    },
    // 当前通话IM对象
    currentMessage() {
      return this.$store.state.currentMessage;
    },
  },
  watch: {
    isMyself(nval,oval){
      if(!oval && nval){ // 本来是多人,只剩下自己,退退退
        setTimeout(() => {
          const currentRoutes = getCurrentPages(); // 获取当前打开过的页面路由数组
          const route = currentRoutes[currentRoutes.length -1].route
          if(route === 'pagesB/meeting/index'){
            uni.showToast({
              title: '没有其他成员，视频终止',
              icon: 'none',
              complete: () => {
                setTimeout(() => {
                  this.sureStopMeeting()
                },1500)
              }
            })
          }
        }, 3000);
      }
    }
  },
  data() {
    return {
      xy_userInfo: {}, // 自己的小鱼用户信息
      rosterList: [], // 会议人列表
      currentCallNumber: "", // 当前主屏人
      isMyself: true, // 会议中是否只有自己
      template: {
        layout: "custom",
        detail: [],
      },
      muted: false, // true 代表开启麦克风，false 代表关闭麦克风，支持动态设置
      camera: true, // true 代表开启摄像头，false 代表关闭摄像头，支持动态设置
      devicePosition: "front", //  front/back 切换前置/后置摄像头,switchCamera方法实现
      operationPanel: false, // 操作面板是否显示
      coloseShow: false, // 挂断二次确认
      callTime: 0, // 通话时间
      callTimeText: "", // 通话时间
      callTimeFn: "", // 通话时间定时器
      memberShow: false, // 成员管理

    };
  },
  onLoad() {
    this.xy_userInfo = uni.getStorageSync("xy_userInfo");
    this._templateFn(); // 初始化布局
  },
  methods: {
    onReady() {
      // this.xylinkRoom = this.$mp.page.selectComponent("#xylink"); // 缓存sdk <xylink-sdk/>组件节点context，为后续调用组件内部方法用
      // this.xylinkRoom.setDebug(true, true); // 日志打印
      const { meetingRoomNumber, password } = this.cellInfo;
      console.log("开始呼叫会议号:", meetingRoomNumber, password);
      XYClient.makeCall({
        number: meetingRoomNumber,
        password: password,
        displayName: this.userInfo.userName || "无名"
      },this.onGetCallStatus);
    },
    // mackCall事件回调，通知是否可以进行入会操作。
    onGetCallStatus(response) {
      console.log(response, "呼叫回调");
      const { code } = response;
      if (code === 200) {
        this.startTime(); // 开始通话计时

        this.$store.dispatch("reportStatus", {
          status: 2,
          orderNo: this.cellInfo.orderNo,
          groupId: this.currentMessage.data.imGroupId
        })
      }
    },

    onUnload() {
      clearTimeout(this.timmer);
      this.callTimeFn = "";
      clearTimeout(this.callTimeFn);
    },
    
    // 小鱼内部事件
    onRoomEvent(ms) {
      console.log(ms,3333333);
      const { type, detail, message } = ms.detail;
      switch (type) {
        case "callStatus":
          if (detail === "connected") {
            // 入会成功
            console.log("11111");
          }
          if (detail === "disconnected") {
            // 异常退会
            console.log("22222");
          }
          break;
        case "roomExit":
          console.log("33333", message);
          break;
        case "roomChange":
          console.log("444444", detail);
          break;
        case "onHold":
          console.log("5555555", detail);
          break;
        case "roster":
          if (detail.rosterV) {
            this.rosterList = [...detail.rosterV];
            this._templateFn(this.currentCallNumber); // 改变布局
          }
        case "event":
          // 点击事件,点击切换主屏
          console.log(message);
          if (!message.target || !message.target.dataset || !message.target.dataset.item) return
          const { item } = message.target.dataset; // 点击的对象
          if (!this.currentCallNumber || item.callNumber === this.currentCallNumber || this.isMyself) {
            // 点击的主屏
            this.operationPanel = !this.operationPanel;
          } else {
            // 点击的分屏
            this._templateFn(item.callNumber); // 改变布局
          }
          break;
        default: {
          console.log("get other message: ", ms.detail);
        }
      }
    },

    onChangeMuted() {
      this.muted = !this.muted;
    },
    onSwitchPosition() {
      const position = this.xylinkRoom.switchCamera();
      this.devicePosition = position;
    },
    onSwitchCamera() {
      this.camera = !this.camera;
    },
    onStopMeeting() {
      this.coloseShow = true;
    },
    // 挂断事件
    sureStopMeeting() {
      const that = this
      if (that.currentMessage.data) {
        // 自己是主持人
        if (that.currentMessage.data.hostId == that.userInfo.id) {
          that.$store.dispatch("sendMessage", {
            groupID: that.currentMessage.data.imGroupId,
            action: "evtImMsgHostAllEndOfCall",
            replyMsg: that.currentMessage,
          });
        } else if (that.template.detail.length === 2) {
          // 两人通话
          that.$store.dispatch("sendMessage", {
            groupID: that.currentMessage.data.imGroupId,
            action: "evtImMsgMemberAllEndOfCall",
            replyMsg: that.currentMessage,
          });
        } else {
          that.$store.dispatch("sendMessage", {
            groupID: that.currentMessage.data.imGroupId,
            action: "evtImMsgHostMemberEndOfCall",
            replyMsg: that.currentMessage,
          });
        }
      }
      that.goPage('/pages/index/index') // 回到首页
      setTimeout(() => {
        that.$store.commit("SET_CURRENTMESSAGE", {});
        that.$store.commit("SET_CELLINFO", {});
        that.$store.dispatch("dissolveGroup"); // 解散群组
        that.$store.dispatch("reportStatus",{status: 3}); // 改为上线
      }, 2000);
    },
    // 布局处理逻辑
    _templateFn(clickCallNumber) {
      // 会议人列表
      const roster = this.rosterList;
      // 处理custom模式自定义布局
      const newDetails = [];
      // 获取第一个roster中的callNumber数据，用来判断是否只有自己
      const fristCallNumber = roster[0] ? roster[0].callNumber : 0;
      // 是否只有自己（roster可能会存在自己的数据）
      this.isMyself = (roster.length === 1 && fristCallNumber === this.xy_userInfo.callNumber) || roster.length === 0;
      // 会中只有自己
      if (this.isMyself) {
        this.template = {
          layout: "custom",
          detail: [
            {
              position: [0, 0, 100, 100],
              callNumber: this.xy_userInfo.callNumber,
              name: this.userInfo.userName || "无名",
              quality: "normal", // normal：180p，high：360p，hd：720p
              isContent: false, // 必填，是否是 Content 画面
            },
          ],
        };
      } else {
        // 入会存在其他人
        roster.forEach((item, index) => {
          // 除去自己
          if (item.callNumber !== this.xy_userInfo.callNumber) {
            // 默认第一个为主屏,前三个为副屏幕,其它隐藏
            const posData =
              index < 3
                ? index === 0
                  ? [0, 0, 75, 100]
                  : [75, 33.3 * index, 25, 33.3]
                : [0, 0, 0, 0];
            newDetails.push({
              position: posData,
              callNumber: item.callNumber,
              name: item.displayName || "无名",
              quality: item.isContent || index === 0 ? "hd" : "normal", // normal：180p，high：360p，hd：720p
              isContent: item.isContent, // 必填，是否是 Content 画面
              roster: item,
            });

            // 设置初始主屏人
            if (index === 0 && !clickCallNumber) {
              this.currentCallNumber = item.callNumber;
            }
          }
        });
        // 将自己追加到第一条数据
        newDetails.unshift({
          position: [75, 0, 25, 33.3],
          callNumber: this.xy_userInfo.callNumber,
          name: this.userInfo.userName || "无名",
          quality: "normal", // normal：180p，high：360p，hd：720p
          isContent: false, // 必填，是否是 Content 画面
        });

        // 点击切换主屏
        if (clickCallNumber) {
          this.currentCallNumber = clickCallNumber; // 切换主屏人
          let i = 0;
          newDetails.forEach((v) => {
            if (v.callNumber === clickCallNumber) {
              v.position = [0, 0, 75, 100];
              v.quality = "hd";
            } else {
              v.position = [75, i * 33.3, 25, 33.3];
              v.quality = "normal";
              i++;
            }
          });
        }

        this.template = Object.assign({}, this.template, {
          detail: newDetails,
        });
      }
      console.log(this.template.detail, "改变布局事件");
    },
    startTime() {
      if (this.callTime) return;
      this.callTimeFn = setInterval(() => {
        this.callTime = this.callTime + 1;
        let min_total = Math.floor(this.callTime / 60); // 总分钟
        let hour_total = Math.floor(min_total / 60); // 小时数
        let min = Math.floor(min_total % 60); // 余分钟
        let sec = Math.floor(this.callTime % 60); // 余秒
        this.callTimeText = `${hour_total < 10 ? "0" : ""}${hour_total}:${
          min < 10 ? "0" : ""
        }${min}:${sec < 10 ? "0" : ""}${sec}`;
      }, 1000);
    },
    openMemberShow() {
      this.operationPanel = false;
      this.memberShow = true;
    },
  },
};
</script>

<style lang="scss" scoped>
.xylink-operate-box {
  position: fixed;
  left: 0;
  bottom: 0;
  width: 100%;
  z-index: 998;
  background: rgba(0, 0, 0, 0.5);
  color: #ffffff;
  font-size: 14px;
  padding: 10px 0;
  .disFlxCC {
    flex: 1;
  }
  .closeBtn {
    background: #ff5454;
    padding: 8px 16px;
    border-radius: 10px;
  }
}
.xylink-operate-box2 {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 998;
  background: rgba(0, 0, 0, 0.5);
  color: #ffffff;
  font-size: 14px;
  padding: 15px 0 15px 0;
}
.memberListBox {
  width: 300px;
  .title {
    font-size: 16px;
    line-height: 50px;
    padding-left: 17px;
    border-bottom: solid 1px #4a4a4a;
  }
  .scrollBox {
    font-size: 14px;
    height: calc(100vh - 50px);
    padding: 0 17px;
    .forBox {
      padding: 6px 0;
      border-bottom: solid 1px #4a4a4a;
      display: flex;
      justify-content: space-between;
      align-items: center;
      .btn1{
        border-radius: 15px;
        border: solid 1px #5A5959;
        padding: 3px 5px;
      }
      .btn2{
        border-radius: 15px;
        border: solid 1px #5A5959;
        padding: 3px 5px;
        background-color: #5A5959;
      }
    }
  }
}
</style>